package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.dto.DishDto;
import com.example.domain.entity.Category;
import com.example.domain.entity.Dish;
import com.example.domain.entity.DishFlavor;
import com.example.domain.entity.SetmealDish;
import com.example.exception.RegisterException;
import com.example.mapper.SetmealDishMapper;
import com.example.mapper.SetmealMapper;
import com.example.service.ICategoryService;
import com.example.service.IDishFlavorService;
import com.example.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 * @author xiaoduan
 * @since 2024-07-30
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private IDishService dishService;

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R page(@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize, @RequestParam(defaultValue = "") String name) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Dish::getSort);
        wrapper.orderByDesc(Dish::getUpdateTime);
        wrapper.like(StringUtils.isNotBlank(name), Dish::getName, name);
        IPage<Dish> dishIPage = new Page<>(page, pageSize);
        IPage<DishDto> dishDtoPage = new Page<>();
        dishService.page(dishIPage, wrapper);
        BeanUtils.copyProperties(dishIPage, dishDtoPage, "records");
        List<DishDto> list = dishIPage.getRecords().stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Category one = categoryService.getById(item.getCategoryId());
            if (one != null) {
                dishDto.setCategoryName(one.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @PostMapping()
    public R saveDish(@RequestBody DishDto dishDto) {
        dishService.saveDishAndDishFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("{id}")
    public R findById(@PathVariable Long id) {
        return R.success(dishService.getDishAndDishFlavorById(id));
    }

    @PutMapping()
    public R update(@RequestBody DishDto dishDto) {
        dishService.updateDishAndDishFlavorByDishDto(dishDto);
        return R.success("更新成功");
    }


    @PostMapping("status/{status}")
    public R tingShouQishouIds(@PathVariable Integer status, String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            Dish byId = dishService.getById(s);
            byId.setStatus(status);
            dishService.updateById(byId);
        }
        return R.success("操作成功");
    }

    @DeleteMapping()
    public R deleteIds(String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            List<SetmealDish> setmealDishes = setmealDishMapper.selectList(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getDishId, s));
            if (!setmealDishes.isEmpty()) {
                throw new RegisterException("存在套餐中包含该菜品，请先删除相关套餐", 601);
            }
            Dish byId = dishService.getById(s);
            if (byId.getStatus() == 1) {
                throw new RegisterException("菜品正在售卖无法删除", 602);
            }
            dishService.removeById(s);
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, byId.getId());
            dishFlavorService.remove(wrapper);
        }
        return R.success("deleteIds操作成功");
    }

    // @GetMapping("/list")
    // public R list(Dish dish) {
    //     LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
    //     wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
    //     wrapper.eq(Dish::getStatus,1);
    //
    //     wrapper.orderByAsc(Dish::getSort);
    //     wrapper.orderByDesc(Dish::getUpdateTime);
    //     List<Dish> list = dishService.list(wrapper);
    //     return R.success(list);
    // }

    @GetMapping("/list")
    public R list(Dish dish) {
        List<DishDto> collect = null;
        // String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        // collect = (List<DishDto>) redisTemplate.opsForValue().get(key);
        // if (collect != null) {
        //     return R.success(collect);
        // }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        wrapper.eq(Dish::getStatus,1);

        wrapper.orderByAsc(Dish::getSort);
        wrapper.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);
        collect = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //根据id查询分类对象
            Category category = categoryService.getById(item.getCategoryId());
            if(category != null){
                dishDto.setCategoryName(category.getName());
            }
            // 菜品口味
            List<DishFlavor> dishFlavors = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, item.getId()));
            if (dishFlavors != null) {
                dishDto.setFlavors(dishFlavors);
            }
            return dishDto;
        }).collect(Collectors.toList());
        // redisTemplate.opsForValue().set(key, collect, 60, TimeUnit.MINUTES);
        return R.success(collect);
    }

}

